<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect, NUpload, NDataTable,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

const model_name = "划扣明细"

defineOptions({ name: model_name })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: model_name,
  initForm: {
    interval:30
  },
  doCreate: api.createConsumablesUse,
  doUpdate: api.updateConsumablesUse,
  doDelete: api.deleteConsumablesUse,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/appointment/project/file',
  deptOption: [],
  gotypeData: [],
  InstiumentData: [],
  ProjectData: [],
  upload: null,
  fileListLength: 0,
  goods:[]
})
onMounted(() => {
  api.getConsumablesType().then((res) => (data.gotypeData = res.data))
  $table.value?.handleSearch()
})

//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}


function  level_format(level,data){
  let ret = ""
  if (data) {
    data.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  }
  
  return ret
}
const columns = [
    {
    title: '+',
    width: 60,
    key: 'buckling_data',
    align: 'center',
    type: 'expand',
    expandable: row => row.buckling_data !== null,
    renderExpand: (row) => {
      let buckling_data = row.buckling_data ?? []
      let sku_columns=[
        {
          width:"auto",
          title: '编号',
          key: 'id'
        },
          {
          width:"auto",
          title: '项目',
          key: 'sku_name'
        }, {
          width:"auto",
          title: '数量',
          key: 'nums'
        },
      ]
      return h(NDataTable, { columns: sku_columns,striped:true ,size:"small",data:buckling_data, style: { width: '1000px',margin:'10px 10px' }  })
    }
  },
    {
    title: '编号',
    key: 'id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },

    {
    title: '门店',
    key: 'space_name',
    width: "auto",
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '客户姓名',
    key: 'user_name',
    width: "auto",
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '对比照-前',
    key: 'before_pic',
    align: 'left',
    width: "auto",
    render(row) {
      const images = row.before_pic ?? []
      const group = []
      for (let i = 0; i < images.length; i++)
        group.push(
            h(NImage,  { src: images[i].url,width: 40 ,height:40,style:"margin-right:2px;border-radius: 5px;"})
        )
      return h('span', group)
    },
  },

    {
    title: '对比照-后',
    key: 'after_pic',
    width: "auto",
    align: 'center',
    render(row) {
      const images = row.after_pic ?? []
      const group = []
      for (let i = 0; i < images.length; i++)
        group.push(
            h(NImage,  { src: images[i].url,width: 40 ,height:40,style:"margin-right:2px;border-radius: 5px;"})
        )
      return h('span', group)
    },
  },{
    title: '技师',
    key: 'designer_names',
    width: "auto",
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '电子签名',
    key: 'e_sign',
    width: "auto",
    align: 'center',
    render(row) {

      return  h(NImage,  { src:row.e_sign,width: 80 ,height:40,style:"margin-right:2px;border-radius: 5px;"})

    }
  },{
    title: '表单',
    key: 'other_form',
    width: "auto",
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '划扣时间',
    key: 'created_at',
    width: "auto",
    align: 'center',
    ellipsis: { tooltip: true },
  },
]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

</script>

<template>

      <CommonPage show-footer :title="model_name">
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSaasBucklingDetail"
          :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="客户" :label-width="40">
              <NInput
                v-model:value="queryItems.user_name"
                clearable
                type="text"
                placeholder="请输入姓名/昵称/手机号"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="录入时间" :label-width="70">
          <NDatePicker
              v-model:value="datetimeRange"
              type="datetimerange"
              clearable
              placeholder="请选择时间范围"
              @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
          </template>
        </CrudTable>

      </CommonPage>

  <!-- 业务页面 -->
</template>
